package com.wuxb.masterWorker;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListSet;

public class Master<T> {

    //1.承装任务的容器
    private ConcurrentLinkedQueue<T> queue = new ConcurrentLinkedQueue<T>();

    //2.使用hashMap来承装所有的worker对象
    private HashMap<String,Thread> workers = new HashMap<String,Thread>();

    //3使用一个容器来存放worker的结果集
    private ConcurrentSkipListSet<Object> resultMap = new ConcurrentSkipListSet<Object>();

    //4.构造方法
    public Master(Worker worker , int workerCount){

        worker.setQueue(queue);
        worker.setResultMap(resultMap);
        for (int i = 0; i < workerCount; i++) {
            workers.put("worker节点"+i,new Thread(worker));
        }
    }

    //5.提交任务
    public void submit(T task){
        this.queue.add(task);
    }

    //6.执行方法：所有worker执行任务
    public void execute(){
        for (Map.Entry<String,Thread> me: workers.entrySet()){
            me.getValue().start();
        }
    }

    //7.判断线程是否执行完毕
    public boolean isComplete(){
        for (Map.Entry<String,Thread> me: workers.entrySet()){
            if (me.getValue().getState() !=Thread.State.TERMINATED){
                return false;
            }
        }
        return true;
    }

    //8.结果
   /* public int getResult(){
        int result = 0;
        for (Object o : resultMap) {
            result+=(Integer) o;
        }
        return result;
    }*/


    public ConcurrentLinkedQueue<T> getQueue() {
        return queue;
    }

    public void setQueue(ConcurrentLinkedQueue<T> queue) {
        this.queue = queue;
    }

    public HashMap<String, Thread> getWorkers() {
        return workers;
    }

    public void setWorkers(HashMap<String, Thread> workers) {
        this.workers = workers;
    }

    public ConcurrentSkipListSet<Object> getResultMap() {
        return resultMap;
    }

    public void setResultMap(ConcurrentSkipListSet<Object> resultMap) {
        this.resultMap = resultMap;
    }
}
